package com.coocaa.x.framework.utils;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class LiteHandlerThread extends HandlerThread {
    private static UncaughtExceptionHandler uncaughtExceptionHandler = new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            LogUtils.e("ERROR", LogUtils.throwable2String(ex));
        }
    };
    private List<Runnable> runnableList = new ArrayList<Runnable>();
    private Handler handler = null;

    public LiteHandlerThread(String name) {
        super(name, android.os.Process.THREAD_PRIORITY_LOWEST);
        setUncaughtExceptionHandler(uncaughtExceptionHandler);
    }

    @Override
    public final void run() {
        super.run();
        synchronized (LiteHandlerThread.this) {
            handler = null;
            runnableList.clear();
        }
    }

    public final void post(Runnable r) {
        postDelayed(r, 0);
    }

    public final synchronized void postDelayed(Runnable r, long delayMillis) {
        if (r == null)
            return;
        if (handler == null)
            handler = new Handler(getLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    Runnable r = (Runnable) msg.obj;
                    r.run();
                    synchronized (runnableList) {
                        runnableList.remove(r);
                    }
                }
            };
        synchronized (runnableList) {
            runnableList.add(r);
        }
        Message msg = new Message();
        msg.obj = r;
        handler.sendMessageDelayed(msg, delayMillis);
    }

    public final List<Runnable> getRunnableList() {
        return runnableList;
    }

    private static Handler uiHandler = null;

    public synchronized static final void postOnUiThread(Runnable r) {
        if (r == null)
            return;
        if (Android.isRunOnMainThread())
            r.run();
        else
            postDelayedOnUiThread(r, 0);

    }

    public synchronized static final void postDelayedOnUiThread(Runnable r, long delayMillis) {
        if (uiHandler == null)
            uiHandler = new Handler(Looper.getMainLooper());
        uiHandler.postDelayed(r, delayMillis);
    }

    public static void checkMainThread() {
        if (Looper.myLooper() == Looper.getMainLooper())
            throw new RuntimeException("Do not call this on main thread!!!");
    }
}
